package br.com.bankai.koby.repository.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import br.com.bankai.koby.repository.entity.PessoaFisica;
import br.com.graflogic.utilities.datautil.repository.BaseRepository;

/**
 * 
 * @author Leonardo
 *
 */
@Repository
public class PessoaFisicaRepository extends BaseRepository<PessoaFisica> {

	public PessoaFisicaRepository() {
		super(PessoaFisica.class);
	}

	

	public PessoaFisica find(PessoaFisica entity) {
		CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
		CriteriaQuery<PessoaFisica> query = builder.createQuery(PessoaFisica.class);
		List<Predicate> predicateList = new ArrayList<Predicate>();

		Root<PessoaFisica> pessoa = query.from(PessoaFisica.class);

		if (StringUtils.isNotEmpty(entity.getCpf())) {
			predicateList.add(builder.and(builder.equal(pessoa.get("cpf"), entity.getCpf())));
		} else {
			predicateList.add(builder.and(builder.equal(pessoa.get("id"), entity.getId())));
		}

		predicateList.add(builder.and(builder.equal(pessoa.get("tipo"), entity.getTipo())));

		query.where(predicateList.toArray(new Predicate[predicateList.size()]));
		TypedQuery<PessoaFisica> typedQuery = getEntityManager().createQuery(query);

		return typedQuery.getSingleResult();
	}
}